/* This file is part of GSMC.
 * 
 * GSMC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GSMC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with GSMC.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.hpxn.gsmc.action;

import net.hpxn.gsmc.config.ConfigFactory;
import net.hpxn.gsmc.config.server.ServerConfigs;
import net.hpxn.gsmc.core.server.Server;
import net.hpxn.gsmc.core.server.exceptions.ServerUnavailableException;
import net.hpxn.gsmc.core.www.servlet.StatusServlet;

import org.apache.log4j.Logger;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class StatusUpdateAction extends BaseAction {
	
	protected Logger log;

	public StatusUpdateAction() {
		log = Logger.getLogger( this.getClass().getCanonicalName() );
	}

	@Override
	public void run() {
		// Enable web server status servlet if enabled.
		try {
			ServerConfigs wServerConfigs = ConfigFactory.getServerConfigs();
			if ( wServerConfigs.getWwwEnabled().equalsIgnoreCase( "true" ) ) {
				ServletContextHandler wServletContext = getEvent().getServer()
						.getServletContext();
				
				wServletContext.addServlet( new ServletHolder(
						new StatusServlet() ), "/status" );
			}
		} catch ( Exception e ) {
			log.error( "Unable to load server configuration in StatusUpdateAction: \n" );
			e.printStackTrace();
		}

		while ( isRunning() ) {
			Server wServer = getEvent().getServer();
			try {
				wServer.updateServerStatus();
				wServer.setUp( true );
				log.info( "[" + getEvent().getServer().getName() + "]"
						+ getEvent().getServer() );
				
			} catch ( ServerUnavailableException e ) {
				wServer.setUp( false );
				log.error( "[" + getEvent().getServer().getName()
						+ "] Could not check the server status: " + e.getMessage() );
			} finally {
				try {
					Thread.sleep( 30000 );
				} catch ( InterruptedException e ) {
					// k.
				}
			}
		}
	}
}
